package com.zyf.project.binaryproto.converter.impl;

import com.zyf.project.binaryproto.converter.DynamicValueConverter;
import org.jetbrains.annotations.NotNull;
import utils.binary.io.BytesInputStream;
import utils.binary.io.BytesOutputBuffer;
import utils.io.NumberMask;

/**
 * <h1>动态值转换器抽象类</h1>
 * <p>实现了 {@link DynamicValueConverter}</p>
 *
 * @author Zhou Yifan
 */
public abstract class AbstractDynamicValueConverter implements DynamicValueConverter {

    /**
     * 值的类型
     */
    protected Class<?> valueType;

    private static final NumberMask SIZE_HEAD = NumberMask.NORMAL;

    private static final byte[] NULL_HEAD = new byte[1];

    static {
        SIZE_HEAD.writeMask(0, NULL_HEAD, 0);
    }

    protected AbstractDynamicValueConverter(Class<?> valueType) {
        this.valueType = valueType;
    }

    /**
     * 获取值的类型
     *
     * @return Class
     */
    @Override
    public Class<?> getValueType() {
        return valueType;
    }

    /**
     * 返回类型的默认初始值；
     *
     * @return Object
     */
    @Override
    public Object getDefaultValue() {
        return null;
    }

    /**
     * 将 size 输送到字节缓冲区
     *
     * @param size   size
     * @param buffer {@link BytesOutputBuffer}
     * @return 写入的字节数
     */
    protected int writeSize(int size, @NotNull BytesOutputBuffer buffer) {
        int length = SIZE_HEAD.getMaskLength(size);
        byte[] headerBytes = new byte[length];
        SIZE_HEAD.writeMask(size, headerBytes, 0);
        buffer.write(headerBytes);
        return length;
    }

    protected int readSize(BytesInputStream bytesInputStream) {
        return (int) SIZE_HEAD.resolveMaskedNumber(bytesInputStream);
    }

}
